package com.xiaochong.tir.manager.controller;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpSession;

import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import com.xiaochong.tir.manager.util.SessionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.pagehelper.PageInfo;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.tir.common.data.po.Navigation;
import com.xiaochong.tir.common.data.po.Role;
import com.xiaochong.tir.common.data.po.RoleNavigation;
import com.xiaochong.tir.common.data.po.SyRotationMap;
import com.xiaochong.tir.manager.filter.SessionManager;
import com.xiaochong.tir.manager.service.NavigationService;
import com.xiaochong.tir.manager.service.RoleNavigationService;
import com.xiaochong.tir.manager.service.RoleService;
import com.xiaochong.tir.manager.util.ManagerVersion;
import com.xiaochong.tir.manager.util.MenuTreeUtil;
import com.xiaochong.tir.manager.util.ReturnResult;


/** 
* @ClassName: RoleController 
* @Description: TODO(角色管理) 
* @author 杨松松
* @date 2018年2月28日 下午2:54:23 
*  
*/
@Controller
@RequestMapping(ManagerVersion.API_V1_PREFIX+"/role")
@Api("角色管理")
public class RoleController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private RoleService roleService;
	@Autowired
    private NavigationService navigationService;
	@Autowired
	private RoleNavigationService roleNavigationService;
	@Autowired
	private RedisServer redisServer;
	/** 
	* @Title: roleList 
	* @Description: TODO(跳转至角色管理列表页) 
	* @param @return  
	* @return String    
	* @throws 
	*/
	@RequestMapping("/roleList")
	public String roleList() {
		return "/account/roleList";
	}

	/** 
	* @Title: listRole 
	* @Description: TODO(查询角色列表) 
	* @param @param limit 
	* @param @param page 
	* @param @param role
	* @param @return  
	* @return Object    
	* @throws 
	*/
	@RequestMapping("/listRole")
	@ResponseBody
	public Object listRole(@RequestParam("limit") int limit, @RequestParam("page") int page, Role role) {
		logger.info(getClass().getSimpleName() + ".listRole()");
		try {
			PageInfo<Role> pageInfo = roleService.listRole(role, page, limit);
			return new ReturnResult<Role>(0, "查询成功！", pageInfo.getList(), pageInfo.getTotal());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("查询角色列表失败:" + e);
			LogTrace.error(getClass().getSimpleName()+"/listRole", e.getMessage(), e);
		}
		return null;
	}

	/** 
	* @Title: roleAdd 
	* @Description: TODO(跳转至角色添加页) 
	* @param @return  
	* @return String    
	* @throws 
	*/
	@RequestMapping("/roleAdd")
	public String roleAdd() {
		return "/account/roleAdd";
	}

	/** 
	* @Title: roleView 
	* @Description: TODO(跳转至角色查看页) 
	* @param @param id
	* @param @param model
	* @param @return  
	* @return String    
	* @throws 
	*/
	@RequestMapping("/roleView")
	public String roleView(@RequestParam("id") Integer id, Model model, HttpSession session) {
		Role role = roleService.getRole(id);
		model.addAttribute("role", role);
		return "/account/roleView";
	}

	/** 
	* @Title: getRole 
	* @Description: TODO(查询角色详细信息) 
	* @param @param id
	* @param @param model
	* @param @return  
	* @return String    
	* @throws 
	*/
	@RequestMapping("/getRole")
	public String getRole(@RequestParam("id") Integer id, Model model) {
		Role role = roleService.getRole(id);
		model.addAttribute("role", role);
		return "/account/roleEdit";
	}

	/** 
	* @Title: saveRole 
	* @Description: TODO(新增角色) 
	* @param @param role
	* @param @param session
	* @param @return  
	* @return Object    
	* @throws 
	*/
	@ApiOperation(value = "新增角色",notes = "新增角色")
	@RequestMapping("/saveRole")
	@ResponseBody
	public Object saveRole(Role role, HttpSession session) {
		redisServer.set(RedisKeysUtils.LOGINNAME,"新增角色");
		logger.info(getClass().getSimpleName() + ".saveRole()");
		try {
			// 校验角色名称是否存在
			int count = roleService.checkRoleName(role);
			if (count > 0) {
				return new ReturnResult<Role>(-1, "角色名称已存在！", 0, count);
			}
			role.setCreatedAt(new Date());
			role.setUpdatedAt(new Date());
			role.setSysUserId(SessionManager.getLoginAccount(session).getId());
			int result = roleService.insertRole(role);
			return new ReturnResult<Role>(0, "新增成功！", result, 0);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("新增角色失败:" + e);
			LogTrace.error(getClass().getSimpleName()+"/saveRole", e.getMessage(), e);
			return new ReturnResult<Role>(-1, "新增失败", 0, 0);
		}
	}

	/** 
	* @Title: updateRole 
	* @Description: TODO(修改角色信息) 
	* @param @param role
	* @param @param session
	* @param @return  
	* @return Object    
	* @throws 
	*/
	@ApiOperation(value = "修改角色信息",notes = "修改角色信息")
	@RequestMapping("/updateRole")
	@ResponseBody
	public Object updateRole(Role role, HttpSession session) {
		redisServer.set(RedisKeysUtils.LOGINNAME,"修改角色信息");
		logger.info(getClass().getSimpleName() + ".updateRole()");
		try {
			// 校验角色名称是否存在
			int count = roleService.checkRoleName(role);
			if (count > 0) {
				return new ReturnResult<Role>(-1, "角色名称已存在！", 0, count);
			}
			role.setUpdatedAt(new Date());
			role.setSysUserId(SessionManager.getLoginAccount(session).getId());
			role.setOperateType((byte)2);
			int result = roleService.updateRole(role,roleService.selectByPrimaryKey(role.getId()));
			return new ReturnResult<Role>(0, "修改成功！", result, 0);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("修改角色失败:" + e);
			LogTrace.error(getClass().getSimpleName()+"/updateRole", e.getMessage(), e);
			return new ReturnResult<Role>(-1, "保存失败", 0, 0);
		}
	}

	/** 
	* @Title: deleteRole 
	* @Description: TODO(删除角色) 
	* @param @param id
	* @param @param session
	* @param @return  
	* @return Object    
	* @throws 
	*/
	@ApiOperation(value = "删除角色",notes = "删除角色")
	@RequestMapping("/deleteRole")
	@ResponseBody
	public Object deleteRole(@RequestParam("id") Integer id, HttpSession session) {
		redisServer.set(RedisKeysUtils.LOGINNAME,"删除角色");
		logger.info(getClass().getSimpleName() + ".deleteRole()");
		try {
			Role role = new Role();
			role.setId(id);
			role.setIsDel((byte) 1);
			role.setOperateType((byte) 3);
			role.setUpdatedAt(new Date());
			role.setSysUserId(SessionManager.getLoginAccount(session).getId());
			int result = roleService.updateRole(role,roleService.selectByPrimaryKey(id));
			return new ReturnResult<Role>(0, "删除成功！", result, 0);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("删除角色失败:" + e);
			LogTrace.error(getClass().getSimpleName()+"/deleteRole", e.getMessage(), e);
			return new ReturnResult<Role>(-1, "删除失败", 0, 0);
		}
	}
	
	/** 
	* @Title: setRoleNavigation 
	* @Description: TODO(跳转至角色权限分配页) 
	* @param @return  
	* @return String    
	* @throws 
	*/
	@RequestMapping("/setRoleNavigation")
	public String setRoleNavigation(@RequestParam("roleId")Integer roleId,Model model) {
		Role role=roleService.getRole(roleId);
		model.addAttribute("role", role);
		return "/account/setRoleNavigation";
	}
	
	
	/** 
	* @Title: getNavigationTree 
	* @Description: TODO(获取菜单tree) 
	* @param @param roleId
	* @param @return
	* @param @throws Exception  
	* @return Object    
	* @throws 
	*/
	@RequestMapping("getNavigationTree")
	@ResponseBody
	public Object getNavigationTree(@RequestParam("roleId")Integer roleId){
		logger.info(getClass().getSimpleName() + ".getNavigationTree()");
		MenuTreeUtil menuTree = new MenuTreeUtil();
		List<Object> menuList = new ArrayList<Object>();
		try {
			Navigation navigation=new Navigation();
			navigation.setRoleId(roleId);
			List<Navigation> list = navigationService.selectByEntityList(navigation);
			menuList = menuTree.menuList(list);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取菜单tree失败:" + e);
			LogTrace.error(getClass().getSimpleName()+"/getNavigationTree", e.getMessage(), e);
		}
		return menuList;
	}
	
	/** 
	* @Title: saveRoleNavigation 
	* @Description: TODO(保存角色权限) 
	* @param @param roleId 角色id
	* @param @param navigationIds 权限id多个值之间逗号分隔
	* @param @param session
	* @param @return  
	* @return Object    
	* @throws 
	*/
	@RequestMapping("/saveRoleNavigation")
	@ResponseBody
	public Object saveRoleNavigation(@RequestParam("roleId") Integer roleId,
			@RequestParam("navigationIds") String navigationIds, HttpSession session) {
		logger.info(getClass().getSimpleName() + ".getNavigationTree()");
		redisServer.set(RedisKeysUtils.LOGINNAME,"角色分配权限");
		try {
			// 删除角色权限
			roleNavigationService.deleteByRoleId(roleId);
			List<RoleNavigation> list = new ArrayList<RoleNavigation>();
			String[] arrays = navigationIds.split(",");
			for (String str : arrays) {
				RoleNavigation roleNavigation = new RoleNavigation();
				roleNavigation.setRoleId(roleId);
				roleNavigation.setNavigationId(Integer.parseInt(str));
				roleNavigation.setSysUserId(SessionManager.getLoginAccount(session).getId());
				list.add(roleNavigation);
			}
			roleNavigationService.insertBatch(list);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("保存角色权限失败:" + e);
			LogTrace.error(getClass().getSimpleName()+"/saveRoleNavigation", e.getMessage(), e);
			return new ReturnResult<Role>(-1, "保存失败", 0, 0);
		}
		return new ReturnResult<Role>(0, "保存角色权限成功！", null, 0);
	}
}
